<template>
  <!-- 编辑当前方案 -->
  <div class="container2">
    <!-- <div class="title">Edit Solution</div> -->
    <div class="tabBox">
      <!-- 详情页 -->

      <div class="JpbBox">
        <span>JABIL COIN</span>
        <a-input-number placeholder v-model="JPB" allowClear class="jpbInput" />
      </div>

      <div class="modelList">
        <div>
          <a-button type="primary" @click="AddMoudule" class="AddModule">AddModule</a-button>

          <a-table :data-source="SchemeInfo.shpSchemeKind" :customRow="clickKindTable ">
            <!-- :row-selection="{ onChange: onSelectChange ,type:'radio'}" -->
            <a-table-column key="KindName" title="KindName" data-index="KindName" />
            <a-table-column key="action" title="Action">
              <template slot-scope="text, record">
                <span>
                  <!-- <a-icon
                        type="edit"
                        theme="twoTone"
                        class="iconBtn"
                        @click="editMoudule(text,record)"
                  />-->
                  <a-icon
                    type="delete"
                    theme="twoTone"
                    class="iconBtn"
                    @click="delMoudule(text,record)"
                  />
                  <a-icon
                    type="plus-circle"
                    theme="twoTone"
                    class="iconBtn"
                    @click="addMouduleModal(text,record)"
                  />
                </span>
              </template>
            </a-table-column>
          </a-table>
        </div>

        <!-- 元器件信息 -->
        <div class="rt">
          <a-button type="primary" @click="AddComponents" class="AddComponents">AddComponents</a-button>
          <a-table :data-source="singleMoudleInfo" :customRow="rowClick">
            <a-table-column key="ProductName" title="ProductName" data-index="ProductName" />

            <a-table-column
              key="ProductParameter"
              title="ProductParameter"
              data-index="ProductParameter"
            >
              <template slot-scope="text,record">
                <div v-html=" text"></div>
              </template>
            </a-table-column>
            <a-table-column key="quantity" title="Quantity" data-index="Quantity">
              <template>
                <div>{{ Quantity }}</div>
              </template>
            </a-table-column>
            <a-table-column key="UnitName" title="UnitName" data-index="UnitName" />
            <!-- TemplatePictrue 图片路径 -->
            <a-table-column key="Images" title="Images" data-index="Images">
              <template slot-scope="text,record">
                <viewer style="width: 150px;height: 150px; overflow: hidden;">
                  <div>
                    <img
                      style="width:110px;height:110px;"
                      v-if="record.Images&&record.Images"
                      :src="record.Images"
                    />
                    <img style="width:110px;height:110px;" v-else src="@/assets/img/noImg.png" />
                    <!-- <span
                      v-else
                      class="NoPictureText"
                      style="font-size:18px;line-height:150px;"
                    >No Picture</span>-->

                    <!-- <span>{{ record }}</span> -->
                  </div>
                </viewer>
              </template>
            </a-table-column>

            <a-table-column key="Price" title="Price" data-index="Price" />
            <a-table-column key="CreateBy" title="CreateBy" data-index="CreateBy" />

            <a-table-column key="Actions" title="Actions">
              <template slot-scope="text,record">
                <div>
                  <a-icon
                    type="edit"
                    theme="twoTone"
                    class="iconBtn"
                    @click="editGoods(text,record)"
                  />
                  <a-icon
                    type="delete"
                    theme="twoTone"
                    class="iconBtn"
                    @click="delGoods(text,record)"
                  />
                </div>
              </template>
            </a-table-column>
          </a-table>
        </div>
      </div>
      <!-- 小计总计区域 -->
      <div>
        <a-form-item label class="totalPriceBox">
          <a-icon type="dollar" theme="twoTone" />
          <span>Sub</span>
          <span>{{ subPrice }}</span>
          <a-icon type="dollar" theme="twoTone" />
          <span>Total</span>
          <span>{{ totalPrice }}</span>
        </a-form-item>
      </div>
    </div>
    <!-- <div class="btnBox">
      <a-button type="primary" class="submitBtn" @click="submitAll">Submit</a-button>
      <a-button type="primary" class="submitBtn" @click="closeEdit">Back</a-button>
    </div>-->
    <!-- 编辑新增元器件弹窗 -->
    <a-modal v-model="visible" :title="modalTitle" @ok="handleOk">
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="ProductName">
          <a-input v-model="ProductName" />
        </a-form-model-item>
        <a-form-model-item label="Image">
          <div :key="ImgKey">
            <imgUpload
              @getAvatar="uploadFileList"
              model="moudleImg"
              :isOpen="isOpen"
              :file="fileList"
              :propImageUrl="ImageUrl"
            ></imgUpload>
          </div>
        </a-form-model-item>
        <a-form-model-item label="Parammeter ">
          <a-textarea v-model="ProductParameter" allow-clear :auto-size="{ minRows: 5}" />
        </a-form-model-item>
        <a-form-model-item label=" Number ">
          <a-input-number v-model="Quantity" />
        </a-form-model-item>
        <a-form-model-item label="Unit  ">
          <a-input v-model="UnitName" />
        </a-form-model-item>
        <a-form-model-item label="Price($) ">
          <a-input v-model="Price" prefix="$" suffix="dollar" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 新增Moudel模组 -->
    <a-modal v-model="moudelVisible" :title="modalTitle" @ok="openModuleOk()">
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="ModuleName">
          <a-input v-model="ModuleName" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import imgUpload from '@/components/upload/AvatarUpload'
import Editor from '@/components/Editor/commonWangEditor'
import VideoUpload from '@/components/upload/videoUpload'
import Header from '@/components/layout/header'
import SemUpload from '@/pageModule/SEM/SmeEdit'

export default {
  name: 'EditScheme',
  data() {
    return {
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      loading: true,
      loadingMore: false,
      showLoadingMore: true,
      data: [],
      componentData: [],
      visible: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 16 }, //表单布局配置
      selectedRowKeys: [], // Check here to configure the default column
      subPrice: 0,
      totalPrice: 0,
      SelectInfo: [],
      SectorInfo: [],
      WorkcellNameInfo: [],
      DivsionInfo: [],
      modalTitle: '',
      // 方案概述
      Department: '',
      Class: '',
      theSector: '',
      theWorkCell: '',
      theDivison: '',
      SolutionName: '',
      SecondTitle: '',
      ImageUrl: '',
      Summary: '',
      Detail: '',
      DetailedInformation: '',
      VideoUrl: '',
      ImageArr: [],
      Sector: '',
      videoList: [],
      // 方案详情
      SectorList: [],
      ProductName: '',
      Price: '',
      goodsImgList: [],
      KindId: '',
      Quantity: 1,
      UnitName: '',
      URL: [],
      Moudeldata: [],
      moudelVisible: false,
      ModuleName: '',
      ProductParameter: '',
      lastParameter: '',
      doType: '',
      ModuleTipIndex: '',
      MoudelList: [],
      SchemeInfo: '',
      singleMoudleInfo: [], //单个模组数据
      clickIndex: 0,
      isOpen: '',
      ImgKey: '',
      Division: '',
      workcellName: '',
      fileList: [],
      UserList: [],
      rowSelection: {
        type: 'radio',
      },
      JPB: 0,
    }
  },
  components: {
    Header,
    imgUpload,
    Editor,
    VideoUpload,
    SemUpload,
  },
  props: ['SchemeId', 'type'],
  computed: {
    // eslint-disable-next-line vue/no-dupe-keys
  },
  watch: {
    visible() {
      if (this.visible) {
        this.ImgKey = ''
      } else {
        this.ImgKey = Math.random()
      }
      console.log('this.ImgKey :>> ', this.ImgKey)
    },
    ProductParameter() {
      this.lastParameter = this.ProductParameter
      // this.lastParameter = this.ProductParameter.replace(/\r\n/g, '<br>')
      //   .replace(/\n/g, '<br>')
      //   .replace(/\s/g, ' ') //转换格式
      // console.log(this.lastParameter, 'lastParameter')
    },
    Price() {},
    Quantity() {
      if (!this.Quantity) {
        this.Quantity = 1
      }
    },
    Sector() {
      this.theSector = this.Sector
    },
    SchemeId() {
      this.getSchemeInfo()
    },
    type(val) {
      console.log('type :>> ', val)
      if (val === 'add') {
        this.SchemeInfo = {}
        this.singleMoudleInfo = []
      } else {
        this.getSchemeInfo()
      }
    },
    JPB(val) {
      if (val < 0) {
        this.JPB = 0
      }
      this.$emit('getJPB', this.JPB)
    },
    videoList() {
      console.log('this.videoList :>> ', this.videoList)
    },
    SchemeId(val) {
      console.log('编辑的方案id :>> ', val)
      this.getSchemeInfo()
    },
  },
  created() {
    this.getRouterData()
    this.getSchemeInfo()
  },

  mounted() {
    this.getSelectInfo()
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log('e :>> ', selectedRowKeys, selectedRows)
    },
    clearData() {},
    initSeotor() {},
    getUserList(e) {
      console.log('父组件 UserList:>> ', e)
      if (e.length > 0) {
        this.UserList = e
      }
    },
    closeEdit() {
      this.$emit('editStatus', false)
    },
    // 点击模块表 单行
    clickKindTable(record, index) {
      const that = this
      return {
        on: {
          click: (event) => {
            console.log('record :>> ', record)
            this.KindId = record.KindId
            // event.target.style.background = 'blue'
            console.log('event :>> ', event.target.style.background)
            this.getSchemeInfo()
            this.KindId = record.KindId
            index = Number(index)
            this.singleMoudleInfo = this.SchemeInfo.shpSchemeKind[
              index
            ].shpSchemeDetailed
            this.clickIndex = index
            console.log('元器件', this.singleMoudleInfo)
            this.subPrice = 0
            if (this.singleMoudleInfo && that.singleMoudleInfo.length >= 0) {
              that.singleMoudleInfo.map((item) => {
                this.subPrice += item.Price
              })
            } else {
              that.singleMoudleInfo = []
              this.subPrice = 0
            }
          },
        },
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        }
      })
    },
    MoudelTableChange(e) {},
    // 生成本页面唯一的方案id
    getUniqueId(randomLength) {
      return Number(
        Math.random().toString().substr(3, randomLength) + Date.now()
      ).toString(36)
    },
    // 查询本页面唯一id的方案详情
    getSchemeInfo() {
      const that = this
      const a = {
        method: 'ShpSchemeInfo_Que',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: 1,
        datas: {
          SchemeId: this.SchemeId,
        },
      }
      // console.log('this.SchmeId :>> ', this.SchemeId)
      if (!this.SchemeId) {
        return
      }
      this.$post(a).then((result) => {
        console.log(result, ' 当前方案', this.clickIndex)
        this.$nextTick(() => {
          this.SchemeInfo = result.data
          this.Division = result.data.Division
          this.ImageArr = eval('(' + result.data.Image + ')')
          this.Sector = result.data.Sector
          this.SectorList[0] = result.data.Sector
          this.DivsionInfo[0] = result.data.Division
          this.WorkcellNameInfo[0] = result.data.Workcell
          this.SolutionName = result.data.SolutionName
          this.SecondTitle = result.data.SecondTitle
          this.workcellName = result.data.Workcell
          this.Summary = result.data.Summary
          this.DetailedInformation = result.data.DetailedInformation
          this.VideoUrl = result.data.Video
          this.videoList[0] = result.data.Video ? result.data.Video : ''
          this.JPB = result.data.JPB
          if (!result.data.shpSchemeKind) {
            this.singleMoudleInfo = []
            return
          }

          let schemeSomeKind =
            result.data.shpSchemeKind.length > 0
              ? result.data.shpSchemeKind
              : []
          if (
            schemeSomeKind[this.clickIndex].shpSchemeDetailed &&
            schemeSomeKind.length > 0
          ) {
            this.KindId = schemeSomeKind[0].shpSchemeDetailed[0].KindId
          } else {
            schemeSomeKind[this.clickIndex].shpSchemeDetailed = []
          }

          that.singleMoudleInfo =
            schemeSomeKind[this.clickIndex].shpSchemeDetailed
          console.log('this.singleMouleInfo :>> ', that.singleMouleInfo)

          this.totalPrice = 0
          schemeSomeKind.map((item) => {
            if (item.shpSchemeDetailed && item.shpSchemeDetailed.length > 0) {
              item.shpSchemeDetailed.map((v) => {
                this.totalPrice += v.Price
              })
            }
          })
        })
      })
    },
    /*模组
     */
    openModuleOk(type) {
      this.moudelVisible = false
      // 新增Moudel模组
      if (!this.ModuleName) {
        return
      }
      if (this.doType == 'add') {
        this.AddMouduleInfo()
      }
      if (this.doType == 'edit') {
        // this.Moudeldata[this.ModuleTipIndex] = this.ModuleName
      }
    },
    //添加，模组
    addMouduleModal(record, text) {
      this.KindId = record.KindId
      this.AddComponents()
      console.log(record, text, '模组')
    },
    AddMoudule() {
      this.doType = 'add'
      this.ModuleName = ''
      this.modalTitle = 'Add Module'
      this.moudelVisible = true
    },
    AddMouduleInfo() {
      const KindId = this.getUniqueId(10)
      if (!this.SchemeId) {
        console.log('没有方案id ')
        return
      }
      const a = {
        method: 'ShpSchemeKind_Add',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: 0,
        datas: {
          SchemeId: this.SchemeId,
          KindId: KindId,
          KindName: this.ModuleName,
        },
      }

      this.MoudelList.push({
        SchemeId: this.SchemeId,
        KindId: KindId,
        KindName: this.ModuleName,
      })
      this.$post(a).then((result) => {
        this.getSchemeInfo()
      })
    },
    // 编辑模组
    editMoudule(item, index) {
      console.log('item :>> ', item)
      this.doType = 'edit'
      this.ModuleName = item.KindName
      this.modalTitle = 'Edit Module'
      this.moudelVisible = true
    },
    //删除模组
    delMoudule(item, index) {
      console.log(item, 'del')
      this.doType = 'del'
      const that = this
      const a = {
        method: 'ShpSchemeKind_Del',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: 0,
        datas: {
          SchemeId: item.SchemeId,
          KindId: item.KindId,
        },
      }
      this.$confirm({
        title: 'warm prompt',
        content: 'Do you want to Delete this data?',
        onOk() {
          that.$post(a).then((result) => {
            if (result.code == 0) {
              that.$message.success('successfully delete!')
              that.getSchemeInfo()
            }
          })
        },
      })
    },
    // 添加元器件
    AddComponents() {
      // 清空数据
      this.ProductName = ''
      this.Quantity = ''
      this.ProductParameter = ''
      this.lastParameter = ''
      this.UnitName = ''
      this.Price = ''
      this.fileList = []
      this.ImageUrl = ''
      this.modalTitle = 'Add Components'
      this.doType = 'add'
      // 校验
      if (this.KindId) {
        this.visible = true
        this.isOpen = true
      } else {
        this.$message.warning('Please select or create a new module to edit!')
      }
    },
    // 删除元器件明细
    delSchemeDetailed(item) {
      const that = this
      console.log('item :>> ', item)
      const a = {
        method: 'ShpSchemeDetailed_Del',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: item.SchemeId,
          KindId: item.KindId,
          ProductName: item.ProductName,
        },
      }
      this.$confirm({
        title: 'warm prompt',
        content: 'Do you want to Delete this data?',
        onOk() {
          that.$post(a).then((result) => {
            if (result.code === 0) {
              console.log(result, '删除方案明细完成')
              that.$message.success('Deleted successfully!')
              that.getSchemeInfo() //刷新表格
            }
          })
        },
      })
    },
    getRouterData() {},

    sectorChange(value, e) {
      // 选择select
      const key = Number(e.key)
      const info = this.SelectInfo[key].workcellName
      this.WorkcellNameInfo = info
      this.theSector = value
    },
    WorkcellChange(value, e) {
      this.workcellName = value
      const key = Number(e.key)
      this.DivsionInfo = this.WorkcellNameInfo[key].customer
    },
    DivisionChange(value, e) {
      this.Division = value
    },
    // 弹窗
    showModal() {
      this.visible = true
      this.isOpen = true
    },
    // 新增或者修改元器件明细
    handleOk(e) {
      // 校验
      if (/\D/.test(this.Price)) {
        this.$message.error('Please enter the correct amount!')
        this.Price = ''
        return
      } else if (!this.ProductName) {
        this.$message.error('Please enter the ProductName!')
        return
      } else if (!this.KindId) {
        this.$message.error('Please Select the Kind!')
        return
      } else if (!this.UnitName) {
        this.$message.error('Please enter the Unit!')
        return
      } else if (!this.Price) {
        this.$message.error('Please enter the Price!')
        return
      }

      const a = {
        method:
          this.doType === 'add'
            ? 'ShpSchemeDetailed_Add'
            : 'ShpSchemeDetailed_Mod',
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: this.SchemeId,
          KindId: this.KindId,
          ProductName: this.ProductName,
          ProductParameter: this.lastParameter,
          Quantity: this.Quantity,
          UnitName: this.UnitName,
          Images: this.ImageUrl,
          Price: this.Price,
        },
      }

      // this.visible = false
      this.$post(a).then((result) => {
        console.log(result)

        if (result.code === 0) {
          this.$message.success('submit successfully!')
          this.getSchemeInfo()
          this.visible = false
          this.isOpen = true
        }
      })
    },
    // 删除元器件
    delGoods(item, index) {
      console.log(item, index)
      const ProductName = item.ProductName
      this.delSchemeDetailed(item)
    },
    editGoods(item, index) {
      this.modalTitle = 'Edit Components'
      console.log('item :>> ', item)
      this.ProductName = item.ProductName
      this.ProductParameter = item.ProductParameter
      this.Quantity = item.Quantity
      this.UnitName = item.UnitName
      this.Price = item.Price
      this.ImageUrl = item.Images
      this.KindId = item.KindId
      this.doType = 'edit'
      this.visible = true
      this.isOpen = true
    },
    // 删除方案
    delScheme() {
      const a = {
        method: 'ShpScheme_Del',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: this.SchemeId,
        },
      }
      this.$post(a).then((result) => {
        result = eval('(' + result + ')')
      })
    },
    //修改方案概述
    addSchemeInstro() {
      const Summary = this.Summary.replace(/\r\n/g, '<br>')
        .replace(/\n/g, '<br>')
        .replace(/\s/g, ' ') //转换格式

      const b = {
        method: 'ShpScheme_Add', //修改方案概述
        userId: window.userId || 1,
        sign: '1',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        datas: {
          SchemeId: this.SchemeId,
          ModuleId: this.ModuleId,
          SubId: this.SubId,
          Sector: this.theSector,
          Workcell: this.workcellName,
          Division: this.Division,
          SchemeType: this.SchemeType,
          SolutionName: this.SolutionName,
          SecondTitle: this.SecondTitle,
          Image: this.ImageUrl,
          Summary: Summary,
          DetailedInformation: this.DetailedInformation.toString(),
          Video: this.VideoUrl,
          PDFAddress: this.PDFAddress,
          UserList: this.UserList,
        },
      }
      let arr1, arr2

      this.$post(b).then((result) => {
        console.log(result)
        arr2 = result
        if (result.code == 0) {
          this.$message.success('successfully Change!')
        }
      })
      return arr1, arr2
    },
    rowClick(record, index) {
      const that = this
      return {
        on: {
          click: (event) => {
            console.log('record :>> ', record)
            this.KindId = record.KindId
          },
        },
      }
    },
    submitAll() {
      if (!this.theSector || !this.workcellName || !this.Division) {
        this.$message.warning(
          'Please select sector, workcell and division first!'
        )
        return
      } else if (!this.SolutionName || !this.SecondTitle) {
        this.$message.warning('Please enter solutionname, secondtitle first!')
        return
      }

      const info = this.addSchemeInstro()
    },
    getSelectInfo() {
      // 获取select数据
      const p = {
        method: 'tb2_workcell_customer_Que',
        userId: window.userId || 1,
        sign: 'A0251DD654CBB418AF1422CA880A1270',
        currentPage: 0,
        limit: 0,
        language: window.language || 1,
        fieldList: '',
        datas: {},
      }

      this.$post(p).then((result) => {
        this.SelectInfo = result.data
      })
    },
    getDetailText(e) {
      // 获取方案Detail 富文本
      if (e) this.DetailedInformation = e
    },
    uploadFileList(e) {
      if (e) {
        this.ImageUrl = e
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import url('css/addProject.less');
.rowSelect {
  background-color: #cbf2ff;
}
</style>